﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Media.Imaging;
using TM.QWeibo.SDK.Objects;

namespace TM.QWeibo.SDK.API
{
    /// <summary>
    /// 与微博相关的接口实现
    /// </summary>
    public class Twitter
        : RequestBase
    {
        /// <summary>
        /// 根据授权对象实例化
        /// </summary>
        /// <param name="oauth"></param>
        public Twitter(OAuth oauth)
            : base(oauth)
        { }

        /// <summary>
        /// 回调方法
        /// </summary>
        Action<ResponseData<Tweet>> CallBack { get; set; }

        /// <summary>
        /// 回调方法
        /// </summary>
        Action<ResponseDataBase<Tweet>> TweetCallBack { get; set; }

        #region 获取一条微博数据

        /// <summary>
        /// 采用默认API请求地址获取一条微博数据
        /// </summary>
        /// <param name="id">微博id</param>
        /// <param name="callback"></param>
        public void GetTweet(string id, Action<ResponseDataBase<Tweet>> callback)
        {
            this.TweetCallBack = callback;
            this.GetTweet("http://open.t.qq.com/api/t/show", id);
        }
        /// <summary>
        /// 获取一条微博数据
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="id">微博id</param>
        /// <returns>获取一条微博数据.</returns>
        private void GetTweet(string requestUrl, string id)
        {
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("id", id);
            this.GetData(requestUrl,parameters,GetTweetEnd);
        }

        /// <summary>
        /// 获取微博结束回调
        /// </summary>
        /// <param name="json"></param>
        private void GetTweetEnd(string json)
        {
            var obj = Util.JsonToObject<ResponseDataBase<Tweet>>(json);
            obj.Data.Users = Util.DesUserList(json);
            if (TweetCallBack != null)
            {
                TweetCallBack(obj);
            }
        }

        #endregion

        #region 发表一条微博

        private Action<ResponseData<TweetOperateResult>> TweetOperateCallback { get; set; }

        /// <summary>
        /// 采用默认API请求地址发表一条微博
        /// </summary>
        /// <param name="content">微博内容</param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public void Add(TweetContent content, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            if (content == null) throw new ArgumentNullException("content");
            this.TweetOperateCallback = callback;
            string requestUrl = content.HasImage ? "http://open.t.qq.com/api/t/add_pic" : "http://open.t.qq.com/api/t/add";
            this.Add(requestUrl, content,syncToQzone);
        }

        /// <summary>
        /// 采用默认API请求地址发表一条微博
        /// </summary>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="callback"></param>
        public void Add(string content, string clientip, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.Add(content, null, clientip, callback,syncToQzone);
        }

        /// <summary>
        /// 采用默认API请求地址发表一条带图片的微博
        /// </summary>
        /// <param name="content">微博内容</param>
        /// <param name="image">附加的本地图片文件地址(绝对地址)</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="callback"></param>
        public void Add(string content, UploadFile image, string clientip, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            var tc = new TweetContent(content, clientip);
            if (image!=null)
            {
                tc.Image = image;
            }
            this.Add(tc,callback,syncToQzone);
        }
        /// <summary>
        /// 发表一条微博
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="content">微博内容</param>
        /// <returns>发表结果</returns>
        private void Add(string requestUrl, TweetContent content, bool syncToQzone = false)
        {
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("content", content.Text);
            parameters.Add("clientip", content.ClientIp);
            parameters.Add("jing", content.Jing);
            parameters.Add("wei", content.Wei);
            parameters.Add("syncflag", syncToQzone ? "0" : "1");
            if (content.HasImage)
            {
                var files = new Files();
                files.Add("pic", content.Image);
                this.PostData(requestUrl, parameters, files, TweetOperateEnd);
            }
            else
            {
                this.PostData(requestUrl, parameters, TweetOperateEnd);
            }
        }

        /// <summary>
        /// 操作结束回调
        /// </summary>
        /// <param name="json"></param>
        public void TweetOperateEnd(string  json)
        {
            if(!string.IsNullOrEmpty(json))
            {
                var rs = Util.JsonToObject<ResponseData<TweetOperateResult>>(json);
                if(this.TweetOperateCallback!=null)
                {
                    this.TweetOperateCallback(rs);
                }
            }

        }

        #endregion

        #region 删除一条微博

        /// <summary>
        /// 采用默认API请求地址删除一条微博
        /// </summary>
        /// <param name="id">微博id</param>
        /// <param name="callback"></param>
        public void Delete(string id, Action<ResponseData<TweetOperateResult>> callback)
        {
            this.TweetOperateCallback = callback;
            this.Delete("http://open.t.qq.com/api/t/del", id,TweetOperateEnd);
        }

        /// <summary>
        /// 删除一条微博
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="id">微博id</param>
        /// <param name="callback"></param>
        /// <returns>删除结果.</returns>
        private void Delete(string requestUrl, string id, Action<string > callback)
        {
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("id", id);
            this.PostData(requestUrl,parameters,null,callback);
        }

        #endregion

        #region 转播一条微博

        /// <summary>
        /// 采用默认API请求地址转播一条微博
        /// </summary>
        /// <param name="reid">转播父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="callback"></param>
        /// <returns>转播结果</returns>
        public void ReAdd(string reid, string content, string clientip, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.ReAdd(reid, content, clientip, null, null,callback,syncToQzone);
        }

        /// <summary>
        /// 采用默认API请求地址转播一条微博
        /// </summary>
        /// <param name="reid">转播父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="jing">经度（可以填空）</param>
        /// <param name="wei">纬度（可以填空）</param>
        /// <param name="callback"></param>
        /// <returns>转播结果</returns>
        public void ReAdd(string reid, string content, string clientip, string jing, string wei, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.ReAdd("http://open.t.qq.com/api/t/re_add", reid, content, clientip, jing, wei,callback,syncToQzone);
        }

        /// <summary>
        /// 转播一条微博
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="reid">转播父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="jing">经度（可以填空）</param>
        /// <param name="wei">纬度（可以填空）</param>
        /// <param name="callback"></param>
        private void ReAdd(string requestUrl, string reid, string content, string clientip, string jing, string wei, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.TweetOperateCallback = callback;
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("content", content);
            parameters.Add("clientip", clientip);
            parameters.Add("jing", jing);
            parameters.Add("wei", wei);
            parameters.Add("reid", reid);
            parameters.Add("syncflag", syncToQzone ? "0" : "1");
            this.PostData(requestUrl, parameters,TweetOperateEnd);
        }

        #endregion

        #region 回复一条微博

        /// <summary>
        /// 采用默认API请求地址回复一条微博
        /// </summary>
        /// <param name="reid">回复的父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="callback"></param>
        public void Reply(string reid, string content, string clientip, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.Reply(reid, content, clientip, null, null, callback,syncToQzone);
        }

        /// <summary>
        /// 采用默认API请求地址回复一条微博
        /// </summary>
        /// <param name="reid">回复的父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="jing">经度（可以填空）</param>
        /// <param name="wei">纬度（可以填空）</param>
        /// <param name="callback"></param>
        public void Reply(string reid, string content, string clientip, string jing, string wei, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.Reply("http://open.t.qq.com/api/t/reply", reid, content, clientip, jing, wei, callback,syncToQzone);
        }

        /// <summary>
        /// 回复一条微博
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="reid">回复的父结点微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="jing">经度（可以填空）</param>
        /// <param name="wei">纬度（可以填空）</param>
        /// <param name="callback"></param>
        private void Reply(string requestUrl, string reid, string content, string clientip, string jing, string wei, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.TweetOperateCallback = callback;
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("content", content);
            parameters.Add("clientip", clientip);
            parameters.Add("jing", jing);
            parameters.Add("wei", wei);
            parameters.Add("reid", reid);
            parameters.Add("syncflag", syncToQzone ? "0" : "1");
            this.PostData(requestUrl, parameters, TweetOperateEnd);
        }
        #endregion

        #region 收藏微博

        /// <summary>
        /// 收藏一条微博
        /// </summary>
        /// <param name="id"></param>
        /// <param name="callback"></param>
        public void AddFavorite(string id, Action<ResponseData<TweetOperateResult>> callback)
        {
            Favorite(id, true, callback);
        }

        /// <summary>
        /// 取消收藏一条微博
        /// </summary>
        /// <param name="id"></param>
        /// <param name="callback"></param>
        public void DelFavorite(string id, Action<ResponseData<TweetOperateResult>> callback)
        {
            Favorite(id, false, callback);
        }

        /// <summary>
        /// 收藏
        /// </summary>
        /// <param name="id">微博ID</param>       
        /// <param name="type">操作类型，true 添加， false 删除</param>
        /// <param name="callback"></param>
        private void Favorite(string id,bool type, Action<ResponseData<TweetOperateResult>> callback)
        {
            TweetOperateCallback = callback;
            var requestUrl = type ? "http://open.t.qq.com/api/fav/addt" : "http://open.t.qq.com/api/fav/delt";
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("id", id);
            this.PostData(requestUrl, parameters, TweetOperateEnd);
        }

        #endregion

        #region 获取单条微博的转播内容/点评列表

        /// <summary>
        /// 采用默认API请求地址获取单条微博的转播内容/点评列表
        /// </summary>
        /// <param name="pageflag">分页标识</param>
        /// <param name="pagetime">本页起始时间（第一页 0，继续：根据返回记录时间决定）</param>
        /// <param name="reqnum">每次请求记录的条数（1-20条）</param>
        /// <param name="tweetid">微博id</param>
        /// <param name="callback"></param>
        public void GetReList(PageFlag pageflag, long pagetime, int reqnum, string rootid, string tweetid, Action<ResponseData<Tweet>> callback)
        {
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("flag", 2);
            parameters.Add("pageflag", (int)pageflag);
            parameters.Add("pagetime", pagetime);
            parameters.Add("reqnum", reqnum);
            parameters.Add("rootid", rootid);
            parameters.Add("twitterid", tweetid);
            GetData("http://open.t.qq.com/api/t/re_list", parameters, (json) => {
                var obj = Util.JsonToObject<ResponseData<Tweet>>(json);
                if (callback!= null)
                {
                    callback(obj);
                }
            });
        }

        #endregion

        #region 对话一条微博

        /// <summary>
        /// 对话一条微博
        /// </summary>
        /// <param name="reid">点评根结点（非父结点）微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="callback"></param>
        public void Comment(string reid, string content, string clientip, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.TweetOperateCallback = callback;
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("content", content);
            parameters.Add("clientip", clientip);
            parameters.Add("reid", reid);
            parameters.Add("syncflag",syncToQzone?"1":"0");
            this.PostData( "http://open.t.qq.com/api/t/comment", parameters, TweetOperateEnd);
        }

        /// <summary>
        /// 对话一条微博
        /// </summary>
        /// <param name="reid">点评根结点（非父结点）微博id</param>
        /// <param name="content">微博内容</param>
        /// <param name="clientip">用户ip(以分析用户所在地)</param>
        /// <param name="jing">经度（可以填空）</param>
        /// <param name="wei">纬度（可以填空）</param>
        /// <param name="callback"></param>
        public void Comment(string reid, string content, string clientip, string jing, string wei, Action<ResponseData<TweetOperateResult>> callback, bool syncToQzone = false)
        {
            this.TweetOperateCallback = callback;
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("content", content);
            parameters.Add("clientip", clientip);
            parameters.Add("reid", reid);
            parameters.Add("jing", jing);
            parameters.Add("wei", wei);
            parameters.Add("syncflag", syncToQzone ? "0" : "1");
            this.PostData("http://open.t.qq.com/api/t/comment", parameters, TweetOperateEnd);
        }

        #endregion

        #region 搜索用户

        /// <summary>
        /// 搜索用户
        /// </summary>
        /// <param name="keyword">搜索关键字</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="pageNum">页码</param>
        /// <param name="callback">回调</param>
        public void Search(string keyword, int pageSize, int pageNum, Action<ResponseDataObject<SDK.Objects.Tweet>> callback)
        {
            var parameters = new Parameters();
            parameters.Add("format", this.ResponseDataFormat.ToString().ToLower());
            parameters.Add("keyword", keyword);
            parameters.Add("pagesize", pageSize.ToString());
            parameters.Add("page", pageNum.ToString());
            parameters.Add("contenttype", "0");
            parameters.Add("sorttype", "0");
            parameters.Add("msgtype", "0");
            parameters.Add("searchtype", "0");
            parameters.Add("starttime", "0");
            parameters.Add("endtime", "0");
            parameters.Add("province", "");
            parameters.Add("city", "");
            parameters.Add("longitude", "");
            parameters.Add("latitude", "");
            parameters.Add("radius", "20000");
            this.GetData(" http://open.t.qq.com/api/search/t", parameters, (jsonStr) =>
            {
                var obj = Util.JsonToObject<ResponseData<SDK.Objects.Tweet>>(jsonStr);
                callback((obj != null && obj.Data != null) ? obj.Data : new ResponseDataObject<SDK.Objects.Tweet>());
            });
        }

        #endregion
    }
}
